# -- coding: utf-8 --
# @Time : 2024/2/5 08:13
# @Author : rlh
# @File : SQLlite_database_utils.py
# 功能描述:  操作数据库

# 系统第三方库

# 导入项目模块

import cx_Oracle


class OracleDatabase:
    def __init__(self, host, port, sid, user, password):
        self.host = host
        self.port = port
        self.sid = sid
        self.user = user
        self.password = password
        self.connection = None
        self.cursor = None

    def connect(self):
        dsn = cx_Oracle.makedsn(self.host, self.port, sid=self.sid)
        self.connection = cx_Oracle.connect(user=self.user, password=self.password, dsn=dsn)
        self.cursor = self.connection.cursor()
        print("Connected to Oracle database successfully.")

    def execute_query(self, query, params=None):
        try:
            self.cursor.execute(query, params)
            return self.cursor.fetchall()
        except cx_Oracle.DatabaseError as e:
            error, = e.args
            print(f"An error occurred: {error.code} - {error.message}")
            return None

    def commit(self):
        self.connection.commit()

    def close_connection(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()
        print("Connection to Oracle database closed.")

    # 使用示例


if __name__ == "__main__":
    # 数据库连接信息
    host = 'your_hostname'
    port = your_port
    sid = 'your_sid'
    user = 'your_username'
    password = 'your_password'

    # 创建OracleDatabase对象
    db = OracleDatabase(host, port, sid, user, password)

    # 连接到数据库
    db.connect()

    # 执行查询
    query = "SELECT * FROM your_table"
    results = db.execute_query(query)
    for row in results:
        print(row)

        # 提交事务（如果需要）
    # db.commit()

    # 关闭连接
    db.close_connection()